package com.secret.view;

import com.secret.service.ConfigService;
import javafx.scene.control.*;
import javafx.scene.input.MouseButton;
import javafx.scene.input.PickResult;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
import javafx.stage.FileChooser;

import java.io.File;
import java.util.List;

public class MainWindow extends HBox {

    private ConfigService configService = ConfigService.getInstance();

    private ListView<Label> listView;

    private VBox right;

    private Editor editor;


    public MainWindow() {
        this.init();
    }

    private void init() {
        VBox left = getLeft();
        left.prefHeightProperty().bind(this.heightProperty());
        getChildren().add(left);

        this.right = getRight();
        getChildren().add(this.right);
    }

    protected VBox getLeft() {
        VBox left = new VBox();
        left.setPrefWidth(200);
        Button button = new Button("打开文件");
        button.setOnAction(event -> {
            doOpenFileChooser();
        });
        button.prefWidthProperty().bind(left.widthProperty());
        this.listView = new ListView<>();
        this.listView.prefHeightProperty().bind(left.heightProperty().subtract(40));

        List<String> files = this.configService.getFiles();
        for (String file : files) {
            File f = new File(file);
            this.listView.getItems().add(new Label(f.getName()));
        }

        // 右键菜单
        ContextMenu contextMenu = new ContextMenu();
        MenuItem menuItem = new MenuItem("删除");
        menuItem.setOnAction(event -> {
            // 删除掉 listView 中对应的项
            Label selectedItem = listView.getSelectionModel().getSelectedItem();
            this.listView.getItems().remove(selectedItem);
            String delFile = configService.getFileByName(selectedItem.getText());
            this.configService.removeFile(delFile);
        });
        contextMenu.getItems().addAll(menuItem);

        this.listView.setOnMousePressed(event -> {
            PickResult pickResult = event.getPickResult();
            // 判断按的鼠标左键
            if (event.getButton() == MouseButton.PRIMARY) {
                contextMenu.hide();
                doListViewClick();
            } else if(event.getButton() == MouseButton.SECONDARY){
                // 添加右键菜单
                Label selectedItem = listView.getSelectionModel().getSelectedItem();
                if(selectedItem == null){
                    return;
                }
                // 显示右键菜单，显示在鼠标点击的位置，注意窗口不一定是全屏的
                contextMenu.show(listView, event.getScreenX(), event.getScreenY());
            }
        });

        left.getChildren().addAll(button, listView);

        return left;
    }

    private void doListViewClick() {
        Label selectedItem = listView.getSelectionModel().getSelectedItem();
        if(selectedItem == null){
            return;
        }
        String text = selectedItem.getText();
        if(this.editor != null && text.equals(this.editor.getTitleName())){
            return;
        }

        String file = this.configService.getFileByName(text);
        VerifyPasswordDialog dialog = new VerifyPasswordDialog();
        dialog.showAndWait();
        String password = dialog.getPassword();
        if (password == null || password.trim().isBlank()) {
            return;
        }

        // 打开编辑器，并且设置内容
        Editor editor = new Editor(new File(file) , password , (v) -> {
            clearContent();
        });
        this.setContent(editor);
    }


    private void setContent(Editor editor){
        this.clearContent();
        this.editor = editor;

        this.right.getChildren().add(this.editor);
        editor.prefWidthProperty().bind(this.right.widthProperty());
        editor.prefHeightProperty().bind(this.right.heightProperty());
    }

    private void clearContent(){
        this.right.getChildren().clear();
        this.editor = null;
    }






    private void doOpenFileChooser() {
        FileChooser fileChooser = new FileChooser();
        String lastOpenDir = configService.getLastOpenDir();
        if (lastOpenDir != null) {
            File file = new File(lastOpenDir);
            if (file.exists()) {
                fileChooser.setInitialDirectory(file);
            } else {
                String homeDir = System.getProperty("user.home");
                fileChooser.setInitialDirectory(new File(homeDir));
            }
        } else {
            String homeDir = System.getProperty("user.home");
            fileChooser.setInitialDirectory(new File(homeDir));
        }

        fileChooser.setTitle("选择一个加密文件");
        File file = fileChooser.showOpenDialog(this.getScene().getWindow());
        if (file == null) {
            return;
        }
        configService.setLastOpenDir(file.getParentFile());

        if (configService.exists(file)) {
            Alert alert = new Alert(Alert.AlertType.WARNING);
            alert.setTitle("提示");
            alert.setContentText("文件重复");
            alert.showAndWait();
            return;
        }

        configService.addFile(file);
        // 显示在listview中
        this.listView.getItems().add(new Label(file.getName()));
    }


    protected VBox getRight() {
        VBox vBox = new VBox();
        vBox.prefWidthProperty().bind(this.widthProperty().subtract(200));
        vBox.prefHeightProperty().bind(this.heightProperty());
        return vBox;
    }
}
